#include "WatchDogSource.h"

namespace Gnodroid {

    Glib::RefPtr<WatchDogSource>
    WatchDogSource::create(sigc::slot<bool> slotCb,
                           gint64 timeout)
    {
        Glib::RefPtr<WatchDogSource> rpWatchDog {new WatchDogSource(slotCb, timeout)};
        return rpWatchDog;
    }

    WatchDogSource::WatchDogSource(sigc::slot<bool> slotCb,
                                   gint64 timeout) :
        m_iTimeout {timeout},
        m_slotCb {slotCb}
    {
        m_iLastTime = g_get_monotonic_time() / 1000;
        connect_generic(slotCb);        //用来注册回调？
    }

    void
    WatchDogSource::feedDog()
    {
        m_iLastTime = g_get_monotonic_time() / 1000;
    }

    bool
    WatchDogSource::prepare(int &timeout)
    {
        gint64 curTime = g_get_monotonic_time() / 1000;
        if (curTime - m_iLastTime > m_iTimeout) {
            return true;        //超时
        }

        timeout = m_iTimeout - (curTime - m_iLastTime);     //修改下一次检查时间爱你
        return false;           //未超时
    }

    bool
    WatchDogSource::check()
    {
        gint64 curTime = g_get_monotonic_time() / 1000;
        if (curTime - m_iLastTime > m_iTimeout) {
            return true;        //检查通过
        }

        return false;           //检查不通过
    }

    bool
    WatchDogSource::dispatch(sigc::slot_base *slot)
    {
        bool result = m_slotCb();       //在本线程执行回调
        if (result) {
            feedDog();                  //根据回调确定是否继续计时
        }
        return result;
    }

}
